package com.bfsd.tieba.agent.tieba_agent.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;

public class SignUtil {
    private static final String SALT = "tiebaclient!!!";

    public static String generateSign(Map<String, String> params) {
        // 1. 参数按key字典序排序
        SortedMap<String, String> sorted = new TreeMap<>(params);
        // 2. 拼接 "key=value" 形式
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : sorted.entrySet()) {
            sb.append(entry.getKey()).append('=').append(entry.getValue());
        }
        // 3. 拼接 salt
        sb.append(SALT);
        // 4. MD5 hash 并转大写
        return md5(sb.toString()).toUpperCase();
    }

    private static String md5(String text) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(text.getBytes(StandardCharsets.UTF_8));
            StringBuilder hex = new StringBuilder();
            for (byte b : digest) {
                hex.append(String.format("%02x", b & 0xff));
            }
            return hex.toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}